package com.trendata.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.trendata.aliyun.AliyunOSSClient;
import com.trendata.domain.Shop;
import com.trendata.domain.User;
import com.trendata.service.CacheService;
import com.trendata.service.ShopService;
import com.trendata.service.UserService;
import com.trendata.util.Constants;
import com.trendata.util.JsonResult;
import com.trendata.util.ResultDO;
import com.trendata.util.TimeUtil;
import com.trendata.util.WeChatUtil;

/**
 * 未登录时的接口
 * 
 * @author: HuangXiuXiu Email:243559392@qq.com
 */
@Controller
@RequestMapping("/home")
public class HomeController {

	private static Logger logger = Logger.getLogger("homeLogger");

	@Autowired
	private UserService userService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private CacheService cacheService;

	/**
	 * 插入店铺
	 * <p>
	 * url=/home/insertShop.do?phone=18768122336&password=xiuxiu123&name=Fo9
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/insertShop")
	@ResponseBody
	public String insertShop(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		String phone = request.getParameter("phone");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		Shop shop = new Shop();
		shop.setPassword(password);
		shop.setPhone(phone);
		shop.setName(name);
		try {
			// 插入店铺
			shopService.insert(shop);
			// 获取店铺的二维码
			ResultDO<Map<String, String>> resultDO = WeChatUtil.createQRCode(cacheService.getAccessToken(TimeUtil.getCurrentHour()),
					(shop.getOpenId() - 99999));
			if (resultDO.isSuccess()) {
				// 获取二维码的图片
				if (resultDO.isSuccess()) {
					Map<String, String> map = resultDO.getModule();
					String ticket = map.get("ticket");
					String url = map.get("url");
					shop.setqRCodeUrl(url);
					shop.setTicket(ticket);
					HttpsURLConnection conn = WeChatUtil.showQRCode(ticket);
					// 上传二维码图片，获取图片地址
					InputStream inputStream = conn.getInputStream();
					ObjectMetadata objectMetadata = new ObjectMetadata();
					objectMetadata.setContentLength(conn.getContentLength());
					objectMetadata.setContentType(conn.getContentType());
					objectMetadata.setContentEncoding("utf-8");
					ResultDO<String> resultDO2 = AliyunOSSClient.putObject("snapshot/shops/" + shop.getOpenId() + "/QRCodeImg.jpg",
							inputStream, objectMetadata);
					conn.disconnect();
					if (resultDO2.isSuccess()) {
						shop.setqRCodeImgUrl(resultDO2.getModule());
						shopService.update(shop);
						result.setSuccess(true);
					} else {
						shopService.deleteByOpenId(shop.getOpenId());
						shop = null;
						result.setMessage("插入店铺信息时上传二维码图片时出现错误：" + resultDO2.getErrMsg());
						logger.error(result.getMessage());
					}
				}
			} else {
				shopService.deleteByOpenId(shop.getOpenId());
				shop = null;
				result.setMessage("获取店铺二维码时出现错误：" + resultDO.getErrMsg());
				logger.error(result.getMessage());
			}
		} catch (Exception e) {
			return result.setMessage("注册店铺出现异常").toJsonString();
		}
		if (shop != null) {
			result.setValue(shop);
			result.setSuccess(true);
		}
		return result.toJsonString();
	}

	/**
	 * 初始化用户,根据openId和shopOpenId返回相应的用户和店铺数据
	 * <p>
	 * home/initUser.do?openId=o7fbYt3cSvjeLnexRgcYJdXhB53Y&shopOpenId=12
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/initUser")
	@ResponseBody
	public String initUser(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		String openId = request.getParameter("openId");
		String shopOpenId = request.getParameter("shopOpenId");
		if (openId == null || openId.equals("") || shopOpenId == null || shopOpenId.equals("")) {
			return result.setMessage("openId不能为空！").toJsonString();
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 获取user
		User user = userService.selectByOpenId(openId);
		if (user == null) {
			return result.setMessage("没有找到该用户").toJsonString();
		}
		resultMap.put("user", user);

		// 获取shop
		Shop shop = shopService.selectByOpenId(Long.valueOf(shopOpenId));
		if (shop != null) {
			shop.setPassword(null);
			shop.setTicket(null);
		}
		resultMap.put("shop", shop);

		// 设置user session信息
		request.getSession().setAttribute(Constants.SESSION_OPEN_ID, openId);
		request.getSession().setAttribute(Constants.SESSION_TYPE, Constants.SESSION_TYPE_USER);
		request.getSession().setAttribute(Constants.SESSION_TYPE_USER, user);
		// 设置用户访问的店铺的session信息
		request.getSession().setAttribute(Constants.SESSION_SHOP_OPEN_ID, shop.getOpenId());

		User user2 = (User) request.getSession().getAttribute(Constants.SESSION_TYPE_USER);
		if (user2 != null) {
			logger.info("成功将user放入session");
		} else {
			logger.info("并未将user放入session");
		}

		result.setValue(shop);
		result.setSuccess(true);
		logger.info("用户：" + user.getOpenId() + "成功登录!");

		result.setValue(resultMap);
		result.setSuccess(true);
		return result.toJsonString();
	}

	/**
	 * 登录店铺，传入相应的openId来获得shop信息
	 * 
	 * <p>
	 * home/loginShop.do?openId=12
	 * </p>
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/loginShop")
	@ResponseBody
	public String loginShop(HttpServletRequest request, HttpServletResponse response) {
		JsonResult result = new JsonResult();
		String openId = request.getParameter("openId");
		if (openId == null || openId.equals("")) {
			return result.setMessage("openId不能为空！").toJsonString();
		}

		Shop shop = shopService.selectByOpenId(Long.valueOf(openId));
		if (shop == null) {
			return result.setMessage("没有找到该店铺").toJsonString();
		}

		// 设置店铺session信息
		request.getSession().setAttribute(Constants.SESSION_OPEN_ID, openId);
		request.getSession().setAttribute(Constants.SESSION_TYPE, Constants.SESSION_TYPE_SHOP);
		request.getSession().setAttribute(Constants.SESSION_TYPE_SHOP, shop);
		result.setValue(shop);
		result.setSuccess(true);
		logger.info("店铺：" + shop.getOpenId() + "成功登录!");
		return result.toJsonString();
	}
	
}
